package cc.magicjson.service.jpa;


import cc.magicjson.entity.User;
import cc.magicjson.jpa.repository.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceJPA {

    private final UserRepository userRepository;

    public UserServiceJPA(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Transactional("jpaTransactionManager")
    public void createUser(User user) {
        userRepository.save(user);
    }

    @Transactional(readOnly = true, transactionManager = "jpaTransactionManager")
    public User getUserById(Long id) {
        return userRepository.findById(id).orElse(null);
    }

    @Transactional(readOnly = true, transactionManager = "jpaTransactionManager")
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @Transactional("jpaTransactionManager")
    public void updateUser(User user) {
        if (userRepository.existsById(user.getId())) {
            userRepository.save(user);
        }
    }

    @Transactional("jpaTransactionManager")
    public void deleteUser(Long id) {
        userRepository.deleteById(id);
    }
}
